<template>
    <div>
        <el-drawer
            :title="
                entryInfo.title +
                (entryInfo.isModule ? '-' : '(明细)-') +
                entryInfo.entryCode +
                (entryInfo.isModule ? '' : '-' + entryInfo.fundCode + '( ' + entryInfo.fundNameSt + ' )')
            "
            :visible.sync="visibleTemp"
            direction="btt"
            size="100%"
            @close="closeModal"
            :close-on-click-modal="false"
        >
            <!-- :style="{ display: entryInfo.isModule ? '' : 'none' }" -->
            <div>
                <el-table
                    :data="tableData"
                    size="mini"
                    row-key="resultId"
                    @row-click="rowClick"
                    :height="entryInfo['isModule'] ? 'calc(50vh - 30px)' : '100px'"
                    border
                    highlight-current-row
                    ref="table"
                >
                    <el-table-column prop="fundCode" label="产品编码" show-overflow-tooltip min-width="105px"> </el-table-column>
                    <el-table-column prop="fundNameSt" label="产品名称" show-overflow-tooltip min-width="105px"> </el-table-column>
                    <el-table-column prop="stockInfos" label="证券代码(名称)" show-overflow-tooltip min-width="105px">
                        <template slot-scope="scope">
                            <el-tag size="small" v-if="scope.row.stockInfos != null && scope.row.stockInfos.length > 1" slot="reference">
                                <el-tooltip placement="top">
                                    <ul slot="content" style="max-height: 200px; overflow: auto">
                                        <li :key="item.dictKey" v-for="item in scope.row.stockInfos">
                                            {{ item.dictKey ? item.dictKey + ':' + item.dictKeyName : item.dictCode }}
                                        </li>
                                    </ul>
                                    <span>{{ scope.row.stockInfos.length + '个证券' }}</span>
                                </el-tooltip>
                            </el-tag>
                            <span v-else-if="scope.row.stockInfos != null && scope.row.stockInfos.length == 1">
                                {{
                                    scope.row.stockInfos[0].dictKey
                                        ? scope.row.stockInfos[0].dictKey + ':' + scope.row.stockInfos[0].dictKeyName
                                        : scope.row.stockInfos[0].dictCode
                                }}
                            </span>
                            <span v-else> --</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="calLogic" label="计算公式" show-overflow-tooltip min-width="105px">
                        <template slot-scope="scope">
                            <span v-if="scope.row.calLogicShow != null">{{ scope.row.calLogicShow }}</span>
                            <span v-else>--</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="阈值" show-overflow-tooltip min-width="85px">
                        <template slot-scope="scope">
                            {{ formatThresholdValue(scope.row) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="calculateValue" label="实际值" show-overflow-tooltip min-width="100px">
                        <template slot-scope="scope">
                            {{ formatCalculateValue(scope.row) || '--' }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="thresholdType" label="触警状态" show-overflow-tooltip min-width="105px">
                        <template slot-scope="scope">
                            <StatusTag :code="scope.row.thresholdType"></StatusTag>
                        </template>
                    </el-table-column>
                    <el-table-column show-overflow-tooltip :formatter="fomatterParam" prop="issueCode" label="发行人编码"></el-table-column>
                    <el-table-column show-overflow-tooltip :formatter="fomatterParam" prop="issueInfoName" label="发行人名称"></el-table-column>
                </el-table>
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    @current-change="getTopPage"
                    :current-page="page.currentPage"
                    :page-size="page.pageSize"
                    :total="page.total"
                    v-show="entryInfo['isModule']"
                >
                </el-pagination>
            </div>

            <el-table
                :data="riskBrandDetail"
                @expand-change="expandChange"
                :expand-row-keys="expandKeys"
                size="mini"
                row-key="brandResultId"
                :height="entryInfo['isModule'] ? 'calc(50vh - 60px)' : 'calc(100vh - 150px)'"
                v-loading="loadingAll"
                :key="'key' + key"
                border
            >
                <!-- :expand-row-keys="expandKeys" -->
                <el-table-column show-overflow-tooltip type="expand">
                    <template slot-scope="scope">
                        <ItemRealTimeStockDetail :data="scope.row.childList" :key="scope.$index" v-loading="loadingDetail" />
                    </template>
                </el-table-column>
                <!-- <el-table-column show-overflow-tooltip prop="branchKey" label="静态分支编码"></el-table-column> -->
                <el-table-column show-overflow-tooltip prop="branchName" label="分支名称"></el-table-column>
                <el-table-column show-overflow-tooltip prop="branchNo" label="分支序号"></el-table-column>
                <el-table-column show-overflow-tooltip prop="branchValue" label="分支计算结果">
                    <template slot-scope="scope">
                        {{ getFormat(scope.row.branchValue) || '--' }}
                    </template>
                </el-table-column>
            </el-table>

            <!-- <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="closeModal">取 消</el-button>
                <el-button size="mini" type="primary" @click="onSubmit">确 定</el-button>
            </div> -->
        </el-drawer>
    </div>
</template>

<script lang="ts">
import { Component, Emit, Prop, PropSync, Vue, Watch } from 'vue-property-decorator';
import DictionConstUtil from '@/utils/diction-const-util';
import { getEntryResultDetail, monitorDetailColumnCache } from '@/pages/risk-monitoring/api';
import { numberFormat, getConfigItem, numberFormatXDAY, numberFormatCIB, unitShow } from '@/utils/tools';
import RiskTable from '@/common/components/risk-table.vue';
import ItemRealTimeStockDetail from './item-real-time-stock-detail.vue';
import StatusTag from '@/pages/risk-measure/components/status-tag.vue';
import XEUtils from 'xe-utils';

@Component({
    name: 'RangeIndicatorsDatasource',
    components: {
        RiskTable,
        ItemRealTimeStockDetail,
        StatusTag,
    },
})
export default class RangeIndicatorsDatasource extends Vue {
    numberFormat = numberFormat;
    numberFormatXDAY = numberFormatXDAY;
    WEB_DOCKING = getConfigItem('WEB_DOCKING');
    // @PropSync('visible') syncVisible: boolean;
    @Prop({
        default: {
            isModule: false,
        },
    })
    entryInfo: any;

    // @Prop({ default: () => [] }) list: any[];

    // @Prop({ default: 1 }) curPage: number;

    private visibleTemp = false;

    tableData: any[] = []; // 表格数据

    private firstRowTemp = {};

    private SourceType = DictionConstUtil.SourceType; // 数据来源信息

    page: any = {
        pageSize: 10,
        currentPage: 1,
        total: 0,
    }; // 分页

    private loadingAll: boolean = false;

    private loadingDetail: boolean = false;

    private expandKeys = []; // 一展开过字段

    // detailData: any[] = []; // 明细数据

    backUp: any = {}; // 备用数据

    private CompareDirection = {
        '0': '>',
        '1': '<',
        '2': '>=',
        '3': '<=',
        '4': '=',
        '5': '<>',
        '6': ' ',
    };

    private ThresholdTypeColor = DictionConstUtil.ThresholdTypeColor;

    private riskBrandDetail = []; // 表格(下)主数据

    isFirst: boolean = true;

    // @Watch('visible')
    // async onWatchVisible(value) {
    //     if (value !== this.visibleTemp) {
    async mounted() {
        console.log('changeVisible');
        // 第一次
        await this.getTopTable(1);
        this.firstRowTemp = this.tableData.length > 0 ? this.tableData[0] : this.firstRowTemp;

        this.visibleTemp = true;
        this.riskBrandDetail = [];

        // 默认选择第一行
        this.tableData.length > 0 && this.rowClick(this.firstRowTemp);
    }
    // }
    getFormat(val) {
        return numberFormatCIB(val);
    }

    formatThresholdValue(row): string {
        if (row.thresholdValue || row.thresholdValue == 0) {
            return this.CompareDirection[row.compareType] + numberFormatCIB(row.thresholdValue, row.unit, 'thresholdValue') + unitShow(row.unit);
        }
        return '--';
    }

    formatCalculateValue(row) {
        if (row.calculateValue || row.calculateValue == 0) {
            return numberFormatCIB(row.calculateValue, row.unit) + unitShow(row.unit);
        }
        return '--';
    }

    async getTopTable(curPage) {
        // 模块
        if (this.entryInfo.isModule) {
            await this.getTopPage(curPage);
        } else {
            this.tableData = [this.entryInfo.row];
        }
    }

    // 模块表格（上）
    async getTopPage(curPage: number) {
        this.page.currentPage = curPage;

        return new Promise((resolve, reject) => {
            getEntryResultDetail({
                entryCode: this.entryInfo.entryCode,
                fundGrCodes: this.entryInfo.searchParam.fundGrCode,
                fundCodes: this.entryInfo.searchParam.fundCodes,
                moduleCode: this.entryInfo.moduleCode,
                paging: this.page,
            })
                .then((res: any) => {
                    this.page.total = res.total;
                    this.tableData = res.list || [];
                    resolve(res);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    // 点击行
    rowClick(row) {
        console.log(this.entryInfo.row?.calBrandNos, this.tableData[0]?.calBrandNos?.trim().split(','), 'this.entryInfo.row?.calBrandNos?');
        console.log('rowClick', this.backUp);
        this.$nextTick(() => {
            (this.$refs.table as any).setCurrentRow(row);
        });
        if (!row.resultId && row.resultId !== 0) {
            return;
        }

        // 是否已点击过
        let value = this.backUp[row.resultId];
        if (value) {
            this.riskBrandDetail = value;
            this.expandKeys = XEUtils.map(this.riskBrandDetail, item => item.brandResultId);
            this.key++;
            return;
        }

        this.loadingAll = true;

        // 明细
        if (!this.entryInfo['isModule']) {
            this.$axios
                .post('/panorama/module/branch/result', {
                    resultId: row.resultId,
                })
                .then((res: any) => {
                    let calBrandNos = this.tableData[0]?.calBrandNos?.trim().split(',');
                    let data = calBrandNos.map(key => res.find(item => item.branchNo == key));
                    res = data;

                    this.riskBrandDetail = res || [];
                    this.loadingAll = false;
                    this.$set(this.backUp, row.resultId, res);
                    this.expandKeys = XEUtils.map(this.riskBrandDetail, item => item.brandResultId);
                    this.getBranchDetail();
                })
                .catch(() => {
                    this.yh_message_error('数据处理异常');
                    this.loadingAll = false;
                });
        } else {
            this.$axios
                .get('/panorama/query/entryBranchResult/' + row.resultId)
                .then((res: any) => {
                    let calBrandNos = this.tableData[0]?.calBrandNos?.trim().split(',');
                    let data = calBrandNos.map(key => res.find(item => item.branchNo == key));
                    res = data;

                    this.riskBrandDetail = res;
                    this.loadingAll = false;
                    this.$set(this.backUp, row.resultId, res);
                    this.expandKeys = XEUtils.map(this.riskBrandDetail, item => item.brandResultId);
                    this.getBranchDetail();
                })
                .catch(() => {
                    this.yh_message_error('数据处理异常');
                    this.loadingAll = false;
                });
        }
    }

    key: number = 1;
    // 获取表格(下)的明细
    getBranchDetail() {
        this.riskBrandDetail.forEach((item, index) => {
            this.loadingDetail = true;
            // 当前分支明细没有数据，要从后台查数据了
            monitorDetailColumnCache({ brandResultId: item.brandResultId, entryCode: item.entryCode })
                .then((result: any) => {
                    this.loadingDetail = false;
                    item.childList = result || [];
                    this.key++;
                })
                .finally(() => {
                    this.loadingDetail = false;
                });
        });
    }

    // 展开下表的行
    expandChange(row, value) {
        console.log(row, value);
        // this.riskBrandDetail.forEach((item, index) => {
        //     if (item.brandResultId === row.brandResultId) {
        //         if (item.childList == undefined) {
        //             // 当前分支明细没有数据，要从后台查数据了
        //             this.loadingDetail = true;
        //             monitorDetailColumnCache({ brandResultId: row.brandResultId, entryCode: row.entryCode })
        //                 .then((result: any) => {
        //                     item.childList = result || [];
        //                     this.expandKeys.push(row.brandResultId);
        //                 })
        //                 .finally(() => {
        //                     this.loadingDetail = false;
        //                 });
        //         }
        //         return;
        //     }
        // });
    }

    // 关闭弹窗
    closeModal() {
        this.visibleTemp = false;
        this.$emit('on-submit', this.page.currentPage);
    }

    fomatterParam(row, column, cellValue) {
        return (cellValue && (cellValue + '').trim()) || cellValue === 0 ? cellValue : '--';
    }
}
</script>
<style scoped lang="scss">
/deep/ .el-drawer__header {
    margin-bottom: 2px;
    padding: 8px;
}
/deep/ .el-table__expanded-cell {
    padding: 1px 2px 2px 48px;
}

/deep/ .el-pagination {
    padding: 5px 5px 5px 0;
}
/deep/ .el-table__body-wrapper {
    overflow-y: auto;
}
</style>
